package com.bfxy.rabbit.common.convert;

import com.bfxy.rabbit.common.serializer.Serializer;
import com.google.common.base.Preconditions;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.messaging.MessageHeaders;

/**
 * @describte:TODO
 * @program:foodie-dev
 * @author:zhengdp
 * @create:2021-09-15 17:03:58
 **/
public class GenericMessageConverter implements MessageConverter {

    private Serializer serializer;

    public GenericMessageConverter(Serializer serializer){
        Preconditions.checkNotNull(serializer);
        this.serializer = serializer;
    }


    /**
     * 写出消息
     * 将消息序列化，将Object对象转换为 AMQP的Message
     * 这个Object对象应该就是我们自定义的Message
     * @param object
     * @param messageProperties
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Message toMessage(Object object,
                             MessageProperties messageProperties)
            throws MessageConversionException {
        return new Message(this.serializer.serializeRaw(object),messageProperties);
    }

    /**
     * 接收消息
     * 传给我们的是Spring的Message，我们要将其转换为自定义的Message
     * @param message
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        // 将 AMQP的Message 转换为我们自定义的Message对象
        byte[] body = message.getBody();
        return this.serializer.deserialize(body);
    }
}
